import { WechatyBuilder } from 'wechaty';
import config from './config.js';
import ChatGPT from './chatgpt.js';
import { onScan } from './onScan.js';
import { onMessage } from './onMessage.js';
import { onRoomJoin } from './onRoomJoin.js';

import { onLogin, onLogout } from './onLogin.js';

const configObj: any = {
	config,
	bot: {},
	startTime: new Date(),
	chatGPTClient: null,
};

async function initProject() {
	try {
		configObj.chatGPTClient = new ChatGPT();
		configObj.bot = WechatyBuilder.build({
			name: config.WechatyName || 'WechatEveryDay',
			puppet: 'wechaty-puppet-wechat', // 如果有token，记得更换对应的puppet
			puppetOptions: {
				uos: true,
			},
		});

		configObj.bot
			.on('scan', (qrcode, code) => onScan(qrcode, code))
			.on('login', (user) => onLogin(user, configObj))
			.on('ready', async () => {
				const contact = await configObj.bot.Contact.find({
					name: '林培坤',
				});
				await contact.say('我启动啦!');
			})
			.on('heartbeat', (msg) => {
				// console.log(`heartbeat -- ${msg}`);
			})
			.on('logout', (user) => onLogout(user))
			.on('message', (msg) => onMessage(msg, configObj))
			.on('friendship', (friendship) =>
				console.log('收到好友请求：' + friendship)
			)
			.on('room-invite', (invitation) =>
				console.log('收到入群邀请：' + invitation)
			)
			.on('room-join', (room, inviteeList, inviter) => onRoomJoin)
			.on('room-leave', (room, leaverList) => {
				// 当机器人把群里某个用户移出群聊的时候会触发这个事件。用户主动退群是无法检测到的。
				const nameList = leaverList.map((c) => c.name()).join(',');
				console.log(`Room ${room.topic()} lost member ${nameList}`);
			})
			.on('room-topic', (room, topic, oldTopic, changer) => {
				// 当有人修改群名称的时候会触发这个事件。
				console.log(
					`Room ${room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`
				);
			});

		configObj.bot
			.start()
			.then(() => console.log('Start to log in wechat...'))
			.catch((e) => console.error(e));
	} catch (error) {
		console.log('init error: ', error);
	}
}

initProject();
